package com.example.demo.scheduledtask;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.common.Constant;
import com.example.demo.config.ErpConfig;
import com.example.demo.entity.ProcurementDetailsRecode;
import com.example.demo.entity.PurchaseReceiptDetailsRecode;
import com.example.demo.mapper.*;
import com.example.demo.utils.SoapXmlUtil;
import com.example.demo.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * TODO 仓库回写ERP数据
 *
 * @author : Zhang.yt
 * @date : 2023/12/6
 */
@Component
@Slf4j
@DS("wms")
public class WmsPurchaseNewCallback {

    @Resource
    private WmsPurchaseNewMapper wmsPurchaseNewMapper;

    @Autowired
    private SoapXmlUtil soapXmlUtil;

    @Autowired
    private PoMpsinfoMapper poMpsinfoMapper;

    @Resource
    private ErpConfig erpConfig;

    @Resource
    private WmsPurchaseMapper wmsPurchaseMapper;


    /**
     * 采购收货回调
     */
//    @Scheduled(fixedDelay = 26 * 1000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void purchaseGet() {
        //查询收货单主表
        PurchaseNotReceiptVo purchaseNotReceiptVo = wmsPurchaseNewMapper.getPurchaseGetNew();
        if (ObjectUtils.isEmpty(purchaseNotReceiptVo) || ObjectUtils.isEmpty(purchaseNotReceiptVo.getPmds055())) {
            //无正常单据需要处理时，将回填超时得单据再重传下(注意，超时得提示信息需要固定，不能修改)
            log.info("未查询到采购收货回调数据，修改报错数据重新过账");
            wmsPurchaseMapper.purchaseGetLose();
            return;
        }
        purchaseNotReceiptVo.setPmdssite(Constant.PMDSSITE_AMA);
        purchaseNotReceiptVo.setActionType(Constant.ActionType_I);
        try {
            //查询收货单细表
            List<PurchaseNotReceiptListVo> purchaseGetListNew = wmsPurchaseNewMapper.getPurchaseGetListNew(purchaseNotReceiptVo.getPmds055());
            if (CollUtil.isEmpty(purchaseGetListNew)) {
                log.info("收货单号:{}细表无数据", purchaseNotReceiptVo.getPmds055());
                wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 2, "细表无数据该单未回写！");
                return;
            }

            //根据采购收货明细获取是采购单号
            Set<String> purchaseOrderNos = purchaseGetListNew.stream().map(PurchaseNotReceiptListVo::getPmdt001).collect(Collectors.toSet());
            //查询采购单采购详情
            if (CollUtil.isEmpty(purchaseOrderNos)) {
                log.info("未获取到采购单信息");
                wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 2, "未获取到采购单信息");
                return;
            }
            //每次都重新拉取下erp采购单，避免ERP修改了和本地不同步
            for (String purchaseOrderNo : purchaseOrderNos) {
                poMpsinfoMapper.syncProcurementDetailsByOrderNo(purchaseOrderNo);
                //更新委外采购可回写项次数据
                poMpsinfoMapper.wmsErpProcurementDetailsPmdnseq(purchaseOrderNo);
            }
            Integer Pmdl005 = wmsPurchaseNewMapper.getPmdl005(purchaseOrderNos);
            if (ObjectUtil.isEmpty(Pmdl005)) {
                log.info("未获取到采购单信息");
                wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 2, "未获取到采购单信息");
                return;
            }
            if (Pmdl005 == 1) {
                purchaseNotReceiptVo.setPmdsdocno(Constant.PMDSDOCNO_3401);
            } else if (Pmdl005 == 3) {
                purchaseNotReceiptVo.setPmdsdocno(Constant.PMDSDOCNO_3402);
            } else {
                purchaseNotReceiptVo.setPmds011(2);
                purchaseNotReceiptVo.setPmdsdocno(Constant.PMDSDOCNO_3410);
            }

            //分批项次信息
            List<ProcurementDetailsVo> procurementDetailsVos = wmsPurchaseMapper.getProcurementDetailsVo(purchaseOrderNos,Pmdl005);
            //没有数据时不会写
            String join = StringUtils.join(purchaseOrderNos, ",");
            if (CollUtil.isEmpty(procurementDetailsVos)) {
                //更新相应表状态为已下发
                wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 2, "对应采购采购单：" + join + "可回写数量不足，该单未回写!");
                return;
            } else {
                //由于可能同一个料分两次收货故要根据料号分组进行计算可回写数量
                Map<String, List<PurchaseNotReceiptListVo>> listMap = purchaseGetListNew.stream().collect(Collectors.groupingBy(PurchaseNotReceiptListVo::getPmdt006));
                for (Map.Entry<String, List<PurchaseNotReceiptListVo>> listEntry : listMap.entrySet()) {
                    String mcode = listEntry.getKey();
                    List<PurchaseNotReceiptListVo> purchaseNotReceiptListVos = listMap.get(listEntry.getKey());
                    //本次料号回填总量
                    BigDecimal returnQty = purchaseNotReceiptListVos.stream().map(PurchaseNotReceiptListVo::getPmdt020).reduce(BigDecimal.ZERO, BigDecimal::add);
                    //采购可收货总数
                    BigDecimal reduce = procurementDetailsVos.stream().filter(item -> item.getPmdn001().equals(mcode)).map(ProcurementDetailsVo::getPmdn007).reduce(BigDecimal.ZERO, BigDecimal::add);
                    //erp已收获数量
                    BigDecimal backQty = procurementDetailsVos.stream().filter(item -> item.getPmdn001().equals(mcode)).map(ProcurementDetailsVo::getReturnQty).reduce(BigDecimal.ZERO, BigDecimal::add);
                    //验退数量
                    BigDecimal pmdt006 = procurementDetailsVos.stream().filter(item -> item.getPmdn001().equals(mcode)).map(ProcurementDetailsVo::getPmdo016).reduce(BigDecimal.ZERO, BigDecimal::add);
                    reduce = reduce.add(pmdt006);
                    if (returnQty.compareTo(reduce.subtract(backQty)) > 0) {
                        //更新相应表状态为已下发
                        wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 2, "料号:" + mcode + "对应采购采购单：" + join + "可回写数量不足，该单未回写!");
                        return;
                    }
                }
            }

            //2024-08-01 新逻辑，新数据默认按照送货单行的采购项次进行抵扣  旧数据按照采购单进行抵扣  待测试
            List<PurchaseNotReceiptListVo> reqList = new ArrayList<>();
            //委外采购情况直接回写不需要计算项次 回写料号为1和6的数据也不需要计算项次
            Integer checkIsWw = wmsPurchaseNewMapper.checkIsWw(purchaseNotReceiptVo.getPmds055());
            if (purchaseNotReceiptVo.getPmds011() == 2 || checkIsWw > 0) {
                for (PurchaseNotReceiptListVo receiptListVo : purchaseGetListNew) {
                    //填充分批序信息
                    receiptListVo.setPmdt004(1);
                    reqList.add(receiptListVo);
                }
            } else {
                //查询erp历史数据
                List<WmsErpSlHistoryData> wmsErpSlHistoryDataList = wmsPurchaseNewMapper.getWmsErpSlHistoryData(purchaseOrderNos);
                for (PurchaseNotReceiptListVo purchaseNotReceiptListVo : purchaseGetListNew) {
                    //采购单号
                    String pmdt001 = purchaseNotReceiptListVo.getPmdt001();
                    //项次
                    Integer pmdt002 = purchaseNotReceiptListVo.getPmdt002();
                    //料号
                    String pmdt006 = purchaseNotReceiptListVo.getPmdt006();
                    //是否历史数据 如果是则按采购单进行计算 料号采购单号是否在erp历史数据中
                    List<ProcurementDetailsVo> procurementDetailsVoList;
                    boolean isHistory = false;
                    if (CollUtil.isNotEmpty(wmsErpSlHistoryDataList)) {
                        //采购单号与料号判定为历史数据
                        List<WmsErpSlHistoryData> collect = wmsErpSlHistoryDataList.stream().filter(item -> item.getMcode().equals(pmdt006) && item.getPmdldocno().equals(pmdt001)).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(collect)) {
                            isHistory = true;
                        }
                    }
                    if (isHistory) {
                        //旧数据使用老的计算方式 需要考虑采购单与料号相同的问题同一送货单不同行号问题
                        procurementDetailsVoList = wmsPurchaseNewMapper.getProcurementDetailsVoListHistory(pmdt001, pmdt006);
                    } else {
                        //新数据 直接按照项次抵扣 分排序随机分配
                        procurementDetailsVoList = wmsPurchaseNewMapper.getProcurementDetailsVoList(pmdt001, pmdt002);
                    }
                    //计算序号并添加到回写数据列表中
                    computeSequenceNumber(procurementDetailsVoList, purchaseNotReceiptListVo, reqList, isHistory);
                }
            }
//            Map<String, List<ProcurementDetailsVo>> collect = procurementDetailsVos.stream().collect(Collectors.groupingBy(ProcurementDetailsVo::getPmdldocno));
//            for (PurchaseNotReceiptListVo purchaseNotReceiptListVo : purchaseGetListNew) {
//                //本次回写数量
//                BigDecimal pmdt020 = purchaseNotReceiptListVo.getPmdt020();
//                //原单的项次在项次中
//                List<ProcurementDetailsVo> collectList = collect.get(purchaseNotReceiptListVo.getPmdt001());
//                for (ProcurementDetailsVo procurementDetailsVo : collectList) {
//                    if (!purchaseNotReceiptListVo.getPmdt006().equals(procurementDetailsVo.getPmdn001())) {
//                        continue;
//                    }
//                    BigDecimal pmdn007 = procurementDetailsVo.getPmdn007();
//                    BigDecimal pmdo016 = procurementDetailsVo.getPmdo016();
//                    BigDecimal returnQty = procurementDetailsVo.getReturnQty();
//                    //本项次可回写数量
//                    BigDecimal subtract = pmdn007.add(pmdo016).subtract(returnQty);
//                    if (subtract.compareTo(BigDecimal.ZERO) == 0) {
//                        continue;
//                    }
//                    PurchaseNotReceiptListVo purchaseNotReceiptListVoCopy = BeanUtil.copyProperties(purchaseNotReceiptListVo, PurchaseNotReceiptListVo.class);
//                    purchaseNotReceiptListVoCopy.setPmdt002(procurementDetailsVo.getPmdnseq());
//                    purchaseNotReceiptListVoCopy.setPmdt003(procurementDetailsVo.getPmdoseq1());
//                    purchaseNotReceiptListVoCopy.setPmdt004(procurementDetailsVo.getPmdoseq2());
//                    if (subtract.compareTo(pmdt020) > 0) {
//                        procurementDetailsVo.setReturnQty(returnQty.add(pmdt020));
//                        purchaseNotReceiptListVoCopy.setPmdt020(pmdt020);
//                        reqList.add(purchaseNotReceiptListVoCopy);
//                        //项次相同时
//                        break;
//                    } else {
//                        purchaseNotReceiptListVoCopy.setPmdt020(subtract);
//                        procurementDetailsVo.setReturnQty(returnQty.add(subtract));
//                        pmdt020 = pmdt020.subtract(subtract);
//                        reqList.add(purchaseNotReceiptListVoCopy);
//                    }
//                    if (pmdt020.compareTo(BigDecimal.ZERO) == 0) {
//                        break;
//                    }
//                }
//            }

            if (CollUtil.isEmpty(reqList)) {
                wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 2, "项次计算失败,请联系开发人员");
                return;
            }
            //获取回写json
            wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 3, "erp待返回");
            String resMessage = soapXmlUtil.getSoapXml("PurchaseGet", "pmds_t", "pmdt_t", purchaseNotReceiptVo, reqList);
            log.info("收货回写:{}", resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            //调用等待
            if (purchaseGetListNew.size() >= 50) {
                Thread.sleep(120 * 1000);
            } else if (purchaseGetListNew.size() >= 30) {
                Thread.sleep(60 * 1000);
            } else if (purchaseGetListNew.size() >= 10) {
                Thread.sleep(30 * 1000);
            } else if (purchaseGetListNew.size() >= 5) {
                Thread.sleep(15 * 1000);
            }
            log.info("soap接口采购收货(新)回调->{}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            //成功
            if (xmlResp.getCode().equals("0")) {
                wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 1, xmlResp.getData().get("pmdsdocno"));
                //因为每次会写都会重新获取，考虑到性能，故这一步注释更新采购单数据
//                for (String orderNo : purchaseOrderNos) {
//                    wmsPurchaseNewMapper.updatePurchaseReceiptDetails(orderNo);
//                }
                //更新回写单据
                poMpsinfoMapper.syncPurchaseReceiptDetails();
                //生成检验单据
                wmsPurchaseNewMapper.wmsQmsCheckSlno(purchaseNotReceiptVo.getPmds055());
            } else {
                //失败
                wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 2, xmlResp.getMessage());
            }
        } catch (Exception e) {
            wmsPurchaseNewMapper.updateStSlOpflg(purchaseNotReceiptVo.getPmds055(), 2, "非常见的数据处理问题，请联系开发人员处理");
            e.printStackTrace();
        }

    }
    private void computeSequenceNumber(List<ProcurementDetailsVo> procurementDetailsVoList, PurchaseNotReceiptListVo purchaseNotReceiptListVo, List<PurchaseNotReceiptListVo> reqList, boolean isHistory) {
        BigDecimal pmdt020 = purchaseNotReceiptListVo.getPmdt020();
        for (ProcurementDetailsVo procurementDetailsVo : procurementDetailsVoList) {
            BigDecimal pmdn007 = procurementDetailsVo.getPmdn007();
            BigDecimal pmdo016 = procurementDetailsVo.getPmdo016();
            BigDecimal returnQty = procurementDetailsVo.getReturnQty();
            //本项次可回写数量 = 采购数量 + 验退数量 - 已回写数量
            BigDecimal subtract = pmdn007.add(pmdo016).subtract(returnQty);
            //历史数据时需要减去回写列表中的数据
            if (isHistory && CollUtil.isNotEmpty(reqList)) {
                BigDecimal reqListNum = BigDecimal.ZERO;
                for (PurchaseNotReceiptListVo receiptListVo : reqList) {
                    //根据采购单号 项次 项序 分批序 加入已经计算的回写数量
                    if (receiptListVo.getPmdt002().equals(procurementDetailsVo.getPmdnseq()) && procurementDetailsVo.getPmdldocno().equals(receiptListVo.getPmdt001())
                            && receiptListVo.getPmdt003().equals(procurementDetailsVo.getPmdoseq1()) && receiptListVo.getPmdt004().equals(procurementDetailsVo.getPmdoseq2())) {
                        reqListNum = reqListNum.add(receiptListVo.getPmdt020());
                    }
                }
                subtract = subtract.subtract(reqListNum);
            }
            if (subtract.compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            PurchaseNotReceiptListVo purchaseNotReceiptListVoCopy = BeanUtil.copyProperties(purchaseNotReceiptListVo, PurchaseNotReceiptListVo.class);
            //项次
            purchaseNotReceiptListVoCopy.setPmdt002(procurementDetailsVo.getPmdnseq());
            //项序
            purchaseNotReceiptListVoCopy.setPmdt003(procurementDetailsVo.getPmdoseq1());
            //分批序
            purchaseNotReceiptListVoCopy.setPmdt004(procurementDetailsVo.getPmdoseq2());
            if (subtract.compareTo(pmdt020) > 0) {
                purchaseNotReceiptListVoCopy.setPmdt020(pmdt020);
                reqList.add(purchaseNotReceiptListVoCopy);
                //项次相同时
                break;
            } else {
                purchaseNotReceiptListVoCopy.setPmdt020(subtract);
                pmdt020 = pmdt020.subtract(subtract);
                reqList.add(purchaseNotReceiptListVoCopy);
            }
            if (pmdt020.compareTo(BigDecimal.ZERO) == 0) {
                break;
            }
        }
    }

    /**
     * 收货检验回写
     */
//    @Scheduled(fixedDelay = 16 * 1000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void genIqcData() {
        GenIqcDataVo genIqcDataNew = wmsPurchaseNewMapper.getGenIqcDataNew();

        if (ObjectUtil.isEmpty(genIqcDataNew) || ObjectUtils.isEmpty(genIqcDataNew.getQcbaud001())) {
            log.info("未查询到收货检验回写数据，修改报错数据重新过账");
            wmsPurchaseMapper.genIqcDataLose();
            return;
        }
        //委外情况
        Integer genIqcDataNewList = wmsPurchaseNewMapper.getGenIqcDataNewList(genIqcDataNew.getQcbaud001());
        //查询关联的报检单数据
        List<SlCallbackListVo> slCallbackList = poMpsinfoMapper.getSlCallbackList(genIqcDataNew.getSlno(), genIqcDataNew.getPmdt001(), genIqcDataNew.getMcode());
        if (CollUtil.isEmpty(slCallbackList)) {
            if (genIqcDataNew.getTc().equals(1)) {
                wmsPurchaseNewMapper.updateStCheckTcOpflg(genIqcDataNew.getQcbaud001(), 2, "未获取到收货回写数据,检验单未回写");
            } else {
                wmsPurchaseNewMapper.updateStCheckOpflg(genIqcDataNew.getQcbaud001(), 2, "未获取到收货回写数据,检验单未回写");
            }
            return;
        }
        //由于可能会返回多个单号保存会写记录
        List<GenIqcDataVo> genIqcDataVoList = new ArrayList<>();
        //设置公共请求信息
        String checkNo = genIqcDataNew.getQcbaud001();
        if (genIqcDataNewList > 1) {
            slCallbackList = poMpsinfoMapper.getSlCallbackListWw(genIqcDataNew.getSlno(), genIqcDataNew.getPmdt001(), genIqcDataNew.getMcode(), checkNo);
            //todo 委外数据全部按合格处理
            BigDecimal genIqcDataNewWw = wmsPurchaseNewMapper.getGenIqcDataNewWw(checkNo);
            computeSlCallbackListWw(genIqcDataNewWw, slCallbackList, genIqcDataVoList, checkNo, genIqcDataNew.getQcba900());
        } else {
            //根据回填数据计算项次项序
//            List<List<SlCallbackListVo>> combinations = findCombinations(slCallbackList, genIqcDataNew.getQcba008());
//            if (CollUtil.isEmpty(combinations)){
//                wmsPurchaseNewMapper.updateStCheckTcOpflg(genIqcDataNew.getQcbaud001(), 2, "计算数据异常");
//                return;
//            }
            //如果合格数量>可回写数量，报错
            BigDecimal pmdt020 = slCallbackList.stream().map(SlCallbackListVo::getPmdt020).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal pmdt053 = slCallbackList.stream().map(SlCallbackListVo::getPmdt053).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal subtract = pmdt020.subtract(pmdt053);
            if (genIqcDataNew.getQcba023().compareTo(subtract) > 0) {
                if (genIqcDataNew.getTc().equals(1)) {
                    wmsPurchaseNewMapper.updateStCheckTcOpflg(genIqcDataNew.getQcbaud001(), 2, "本次回写数量:" + genIqcDataNew.getQcba023() + "大于可回写数量:" + subtract + ",请确认");
                } else {
                    wmsPurchaseNewMapper.updateStCheckOpflg(genIqcDataNew.getQcbaud001(), 2, "本次回写数量:" + genIqcDataNew.getQcba023() + "大于可回写数量:" + subtract + ",请确认");
                }
                return;
            }
            genIqcDataNew.setActionType(Constant.ActionType_I);
            genIqcDataNew.setQcbadocno(Constant.PMDSDOCNO_3433);
            genIqcDataNew.setQcbasite(Constant.PMDSSITE_AMA);
            //数据计算
            computeSlCallbackList(genIqcDataNew, slCallbackList, genIqcDataVoList);
        }

        try {
            if (genIqcDataVoList.size() == 1) {
                GenIqcDataVo genIqcDataVo = genIqcDataVoList.get(0);
                //获取回写json
                String resMessage = soapXmlUtil.getSoapXml("GenIqcData", "qcba_t", genIqcDataVo);
//                String replaceAll = resMessage.replaceAll("value='100.00000000'", "value='40.00000000'");

                sendIqcMessageNew(genIqcDataVo.getQcba001(), genIqcDataNew, checkNo, resMessage, 1);
            } else {
                //获取回写json
                String resMessage = soapXmlUtil.getSoapXmlList("GenIqcData", "qcba_t", genIqcDataVoList);
                sendIqcMessageNew(genIqcDataVoList.get(0).getQcba001(), genIqcDataNew, checkNo, resMessage, genIqcDataVoList.size());
            }
        } catch (Exception e) {
            if (genIqcDataNew.getTc().equals(1)) {
                wmsPurchaseNewMapper.updateStCheckTcOpflg(checkNo, 2, "非常见的数据处理问题，请联系开发人员处理");
            } else {
                wmsPurchaseNewMapper.updateStCheckOpflg(checkNo, 2, "非常见的数据处理问题，请联系开发人员处理");
            }
            e.printStackTrace();
        }
    }

    private void sendIqcMessageNew(String qcba001, GenIqcDataVo genIqcDataNew, String checkNo, String resMessage, int size) throws InterruptedException {
        log.info("soapIQC质检请求:->{}", resMessage);
        if (genIqcDataNew.getTc().equals(1)) {
            wmsPurchaseNewMapper.updateStCheckTcOpflg(checkNo, 3, "erp待返回");
        } else {
            wmsPurchaseNewMapper.updateStCheckOpflg(checkNo, 3, "erp待返回");
        }
        //获取回写json
        //发送soap消息，并解析结果
        String result;
        try {
            result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
        } catch (Exception e) {
            result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
        }
        if (size >= 200) {
            Thread.sleep(150 * 1000);
        } else if (size >= 100) {
            Thread.sleep(90 * 1000);
        } else if (size >= 50) {
            Thread.sleep(60 * 1000);
        } else if (size >= 30) {
            Thread.sleep(20 * 1000);
        } else if (size >= 10) {
            Thread.sleep(10 * 1000);
        } else if (size >= 5) {
            Thread.sleep(5 * 1000);
        }
        //每一次调用等待3秒钟时间返回数据--防止回写成功后数据出现异常
        log.info("soap接口IQC质检返回:->{}", result);
        XmlResp xmlResp = soapXmlUtil.analysisXml(result);
        //成功
        if (xmlResp.getCode().equals("0")) {
            if (genIqcDataNew.getTc().equals(1)) {
                wmsPurchaseNewMapper.updateStCheckTcOpflg(checkNo, 1, xmlResp.getData().get("qcbadocno"));
            } else {
                wmsPurchaseNewMapper.updateStCheckOpflg(checkNo, 1, xmlResp.getData().get("qcbadocno"));
            }
            //更新回写单据可入库量
//                poMpsinfoMapper.syncPurchaseReceiptDetails();
            wmsPurchaseNewMapper.updatePurchaseReceiptDetails(qcba001);
        } else {
            if (genIqcDataNew.getTc().equals(1)) {
                wmsPurchaseNewMapper.updateStCheckTcOpflg(checkNo, 2, xmlResp.getMessage());
            } else {
                wmsPurchaseNewMapper.updateStCheckOpflg(checkNo, 2, xmlResp.getMessage());
            }
        }
    }

    private void computeSlCallbackListWw(BigDecimal qcba008, List<SlCallbackListVo> slCallbackList, List<GenIqcDataVo> genIqcDataVoList, String checkNo, String qcba900) {
        Date date = new Date();
        //由于数量是合并，需要计算后回写
        for (SlCallbackListVo slCallbackListVo : slCallbackList) {
            GenIqcDataVo genIqcDataVoReq = new GenIqcDataVo();
            //防止单号重复这里回写单号为：质检单号 + 报检项次
            genIqcDataVoReq.setQcbaud001(checkNo + '-' + slCallbackListVo.getPmdtseq());
            genIqcDataVoReq.setQcba001(slCallbackListVo.getPmdsdocno());
            genIqcDataVoReq.setQcba002(slCallbackListVo.getPmdtseq());
            genIqcDataVoReq.setActionType(Constant.ActionType_I);
            genIqcDataVoReq.setQcbadocno(Constant.PMDSDOCNO_3433);
            genIqcDataVoReq.setQcbasite(Constant.PMDSSITE_AMA);
            genIqcDataVoReq.setQcbadocdt(date);
            genIqcDataVoReq.setQcba900(qcba900);
            //剩余可收数量
            BigDecimal subtract = slCallbackListVo.getPmdt020().subtract(slCallbackListVo.getPmdt053());
            //合格： 合格数量>收料数量:收料数量 else 合格数量
            if (qcba008.compareTo(subtract) > 0) {
                //收料数量大于等于本项次的数量
                genIqcDataVoReq.setQcba008(subtract);
                qcba008 = qcba008.subtract(subtract);
                genIqcDataVoReq.setQcba023(subtract);
                genIqcDataVoReq.setQcba027(BigDecimal.ZERO);
            } else {
                genIqcDataVoReq.setQcba008(qcba008);
                genIqcDataVoReq.setQcba023(qcba008);
                genIqcDataVoReq.setQcba027(BigDecimal.ZERO);
                qcba008 = BigDecimal.ZERO;
            }
            genIqcDataVoList.add(genIqcDataVoReq);
            if (qcba008.compareTo(BigDecimal.ZERO) == 0) {
                break;
            }
        }
    }

    /**
     * 采购上架回写
     */
//    @Scheduled(fixedDelay = 29 * 1000)//开启定时同步
//    @Async(value = "taskExecutor")
    public void purchaseIn() {
        //查询待回写的上架单
        PurchaseReceiptFormVo purchaseReceiptFormVo = wmsPurchaseNewMapper.getPurchaseIn();

        if (ObjectUtil.isEmpty(purchaseReceiptFormVo) || ObjectUtil.isEmpty(purchaseReceiptFormVo.getPmds055())) {
            log.info("未查询到采购上架回调数据，修改报错数据重新过账");
            wmsPurchaseMapper.purchaseInLose();
            return;
        }
        //来源单号
        String pmds055 = purchaseReceiptFormVo.getPmds055();
        //查询要回写的细表
        List<PurchaseReceiptFormListReq2> purchaseReceiptFormListReq2s = wmsPurchaseNewMapper.getgetPurchaseInListNew(purchaseReceiptFormVo.getPmds055());
        if (CollUtil.isEmpty(purchaseReceiptFormListReq2s)) {
            wmsPurchaseNewMapper.updatePurchaseInOpflg(purchaseReceiptFormVo.getPmds055(), 2, "明细列表为空请确认！");
            return;
        }
        List<String> mcodeList = purchaseReceiptFormListReq2s.stream().map(PurchaseReceiptFormListReq2::getPmdt006).distinct().collect(Collectors.toList());
        //查询送货单关联收货单可入库数据
        List<SlStoreableVo> slStoreableVoList = wmsPurchaseNewMapper.getSlStoreableVoList(purchaseReceiptFormVo.getSourceid(), mcodeList);
        if (CollUtil.isEmpty(slStoreableVoList)) {
            wmsPurchaseNewMapper.updatePurchaseInOpflg(purchaseReceiptFormVo.getPmds055(), 2, "查询到的erp可入库数量为空，请确认！");
            return;
        } else {
            //料号可入库数量是否足够
            for (PurchaseReceiptFormListReq2 purchaseReceiptFormListReq2 : purchaseReceiptFormListReq2s) {
                //入库上架数量
                BigDecimal pmdt020 = purchaseReceiptFormListReq2.getPmdt020();
                BigDecimal reduce = slStoreableVoList.stream().filter(item -> purchaseReceiptFormListReq2.getPmdt006().equals(item.getPmdt006())
                        && purchaseReceiptFormListReq2.getPmdt018().equals(item.getPmdt018())).map(SlStoreableVo::getQty).reduce(BigDecimal.ZERO, BigDecimal::add);
                if (pmdt020.compareTo(reduce) > 0) {
                    wmsPurchaseNewMapper.updatePurchaseInOpflg(purchaseReceiptFormVo.getPmds055(), 2, "料号:" + purchaseReceiptFormListReq2.getPmdt006() + "批次:" + purchaseReceiptFormListReq2.getPmdt018() + "查询到的erp可入库数量为空，请确认！");
                    return;
                }
            }
        }
        try {
            purchaseReceiptFormVo.setActionType(Constant.ActionType_I);
            purchaseReceiptFormVo.setPmdssite(Constant.PMDSSITE_AMA);
            List<PurchaseReceiptFormListReq2> sendReqList = new ArrayList<>();

            Map<String, List<SlStoreableVo>> collect = slStoreableVoList.stream().collect(Collectors.groupingBy(SlStoreableVo::getPmdsdocno));
            if (collect.keySet().size() > 1) {
                //多个收货单收货情况
                for (PurchaseReceiptFormListReq2 purchaseReceiptFormListReq2 : purchaseReceiptFormListReq2s) {
                    //回写数量
                    BigDecimal pmdt020 = purchaseReceiptFormListReq2.getPmdt020();
                    for (Map.Entry<String, List<SlStoreableVo>> listEntry : collect.entrySet()) {
                        computeItem(listEntry.getValue(), pmdt020, sendReqList, purchaseReceiptFormListReq2);
                        //上架数量为0时跳出循环
                        if (pmdt020.compareTo(BigDecimal.ZERO) <= 0) {
                            break;
                        }
                    }
                }
            } else {
                //单个收货单直接计算项次
                String pmdsdocno = slStoreableVoList.get(0).getPmdsdocno();
                purchaseReceiptFormVo.setPmds006(pmdsdocno);
                for (PurchaseReceiptFormListReq2 purchaseReceiptFormListReq2 : purchaseReceiptFormListReq2s) {
                    //回写数量
                    BigDecimal pmdt020 = purchaseReceiptFormListReq2.getPmdt020();
                    computeItem(slStoreableVoList, pmdt020, sendReqList, purchaseReceiptFormListReq2);
                }
            }
            //
            if (CollUtil.isEmpty(sendReqList)) {
                wmsPurchaseNewMapper.updatePurchaseInOpflg(purchaseReceiptFormVo.getPmds055(), 2, "数据分发项次失败，请联系开发人员处理");
                return;
            }
            //如果有多个收货单的情况则需要分开回写
            Map<String, List<PurchaseReceiptFormListReq2>> listMap = sendReqList.stream().collect(Collectors.groupingBy(PurchaseReceiptFormListReq2::getPmds006));
            if (listMap.keySet().size() > 1) {
                ArrayList<String> pmdsdocnoList = new ArrayList<>();
                for (Map.Entry<String, List<PurchaseReceiptFormListReq2>> listEntry : listMap.entrySet()) {
                    purchaseReceiptFormVo.setPmds055(pmds055 + "-" + System.currentTimeMillis());
                    if (ObjectUtil.isEmpty(purchaseReceiptFormVo.getPmds011())) {
                        purchaseReceiptFormVo.setPmds011(collect.get(listEntry.getKey()).get(0).getPmds011());
                        purchaseReceiptFormVo.setPmdsdocno(purchaseReceiptFormVo.getPmds011() == 1 ? Constant.PMDSDOCNO_3501 : Constant.PMDSDOCNO_3510);
                    }
                    purchaseReceiptFormVo.setPmds006(listEntry.getKey());
                    //获取回写json
                    String resMessage = soapXmlUtil.getSoapXml("PurchaseIn", "pmds_t", "pmdt_t", purchaseReceiptFormVo, listEntry.getValue());
                    log.info("采购入库回写:{}", resMessage);
                    wmsPurchaseNewMapper.updatePurchaseInOpflg(pmds055, 3, "erp待返回");
                    //发送soap消息，并解析结果
                    String result;
                    try {
                        result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
                    } catch (Exception e) {
                        result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
                    }
                    //调用等待
                    if (listEntry.getValue().size() >= 50) {
                        Thread.sleep(100 * 1000);
                    } else if (listEntry.getValue().size() >= 30) {
                        Thread.sleep(60 * 1000);
                    } else if (listEntry.getValue().size() >= 10) {
                        Thread.sleep(30 * 1000);
                    } else if (listEntry.getValue().size() >= 5) {
                        Thread.sleep(10 * 1000);
                    }
                    log.info("soap接口采购入库回调->{}", result);
                    XmlResp xmlResp = soapXmlUtil.analysisXml(result);
                    if (xmlResp.getCode().equals("0")) {
                        pmdsdocnoList.add(xmlResp.getData().get("pmdsdocno"));
                        //更新wms已回填数量
                        for (PurchaseReceiptFormListReq2 listReq2 : listEntry.getValue()) {
                            if (ObjectUtil.isNotEmpty(listReq2.getPmdt017())) {
                                listReq2.setPmdt016(listReq2.getPmdt016() + "#" + listReq2.getPmdt017());
                            }
                            wmsPurchaseNewMapper.updatePurchaseInreturnQty(listReq2, pmds055);
                        }
                        //更新erp收货单已入库数量
                        wmsPurchaseNewMapper.updatePurchaseReceiptDetails(purchaseReceiptFormVo.getPmds006());
                    } else {
                        //更新相应主表状态为回填失败
                        wmsPurchaseNewMapper.updatePurchaseInOpflg(pmds055, 2, xmlResp.getMessage());
                        return;
                    }
                }
                String join = StringUtils.join(pmdsdocnoList, ",");
                //更新相应主表状态为回填成功
                wmsPurchaseNewMapper.updatePurchaseInOpflg(pmds055, 1, join);
                //更新wsm及仓库上上架入库数量
                wmsPurchaseNewMapper.wmsSrmUpStockqty(purchaseReceiptFormVo.getPmds055());
            } else {
                if (ObjectUtil.isEmpty(purchaseReceiptFormVo.getPmds011())) {
                    purchaseReceiptFormVo.setPmds011(slStoreableVoList.get(0).getPmds011());
                    purchaseReceiptFormVo.setPmdsdocno(purchaseReceiptFormVo.getPmds011() == 1 ? Constant.PMDSDOCNO_3501 : Constant.PMDSDOCNO_3510);
                }
                purchaseReceiptFormVo.setPmds006(sendReqList.get(0).getPmds006());
                purchaseReceiptFormVo.setPmds055(purchaseReceiptFormVo.getPmds055() + '-' + System.currentTimeMillis());
                //获取回写json
                String resMessage = soapXmlUtil.getSoapXml("PurchaseIn", "pmds_t", "pmdt_t", purchaseReceiptFormVo, sendReqList);
                log.info("采购入库回写:{}", resMessage);
                wmsPurchaseNewMapper.updatePurchaseInOpflg(pmds055, 3, "erp待返回");
                //发送soap消息，并解析结果
                String result;
                try {
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
                } catch (Exception e) {
//                    log.info("采购入库回写调用erp接口异常，尝试调用url2");
                    result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
                }
                //调用等待
                if (sendReqList.size() >= 50) {
                    Thread.sleep(100 * 1000);
                } else if (sendReqList.size() >= 30) {
                    Thread.sleep(60 * 1000);
                } else if (sendReqList.size() >= 10) {
                    Thread.sleep(30 * 1000);
                } else if (sendReqList.size() >= 5) {
                    Thread.sleep(10 * 1000);
                }
                log.info("soap接口采购入库回调->{}", result);
                XmlResp xmlResp = soapXmlUtil.analysisXml(result);
                if (xmlResp.getCode().equals("0")) {
                    //更新相应主表状态为回填成功
                    wmsPurchaseNewMapper.updatePurchaseInOpflg(pmds055, 1, xmlResp.getData().get("pmdsdocno"));
                    //更新wms已回填数量
                    for (PurchaseReceiptFormListReq2 listReq2 : sendReqList) {
                        if (ObjectUtil.isNotEmpty(listReq2.getPmdt017())) {
                            listReq2.setPmdt016(listReq2.getPmdt016() + "#" + listReq2.getPmdt017());
                        }
                        wmsPurchaseNewMapper.updatePurchaseInreturnQty(listReq2, pmds055);
                    }
                    //更新erp收货单已入库数量
                    wmsPurchaseNewMapper.updatePurchaseReceiptDetails(purchaseReceiptFormVo.getPmds006());
                    //更新wsm及仓库上上架入库数量
                    wmsPurchaseNewMapper.wmsSrmUpStockqty(pmds055);
                } else {
                    //更新相应主表状态为回填失败
                    wmsPurchaseNewMapper.updatePurchaseInOpflg(pmds055, 2, xmlResp.getMessage());
                }
            }
        } catch (Exception e) {
            wmsPurchaseNewMapper.updatePurchaseInOpflg(pmds055, 2, "非常见的数据处理问题，请联系开发人员处理");
            e.printStackTrace();
        }

    }

    private void computeItem(List<SlStoreableVo> slStoreableVoList, BigDecimal pmdt020, List<PurchaseReceiptFormListReq2> sendReqList, PurchaseReceiptFormListReq2 purchaseReceiptFormListReq2) {
        List<SlStoreableVo> slStoreableVos = slStoreableVoList.stream().filter(item -> purchaseReceiptFormListReq2.getPmdt006().equals(item.getPmdt006())
                && purchaseReceiptFormListReq2.getPmdt018().equals(item.getPmdt018())).collect(Collectors.toList());
        //有多个项次数据时需要分发项次及数量
        for (SlStoreableVo slStoreableVo : slStoreableVos) {
            PurchaseReceiptFormListReq2 copyProperties = BeanUtil.copyProperties(purchaseReceiptFormListReq2, PurchaseReceiptFormListReq2.class);
            copyProperties.setPmdt028(slStoreableVo.getPmdtseq());
            copyProperties.setPmds006(slStoreableVo.getPmdsdocno());
            if (pmdt020.compareTo(slStoreableVo.getQty()) > 0) {
                copyProperties.setPmdt020(slStoreableVo.getQty());
                pmdt020 = pmdt020.subtract(slStoreableVo.getQty());
            } else {
                copyProperties.setPmdt020(pmdt020);
                pmdt020 = BigDecimal.ZERO;
            }
            sendReqList.add(copyProperties);
            if (pmdt020.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
        }
    }


    private void computeSlCallbackList(GenIqcDataVo genIqcDataNew, List<SlCallbackListVo> slCallbackList, List<GenIqcDataVo> genIqcDataVoList) {
        //合格数量
        BigDecimal qcba023 = genIqcDataNew.getQcba023();
        if (qcba023.compareTo(new BigDecimal(0E-8)) == 0) {
            qcba023 = BigDecimal.ZERO;
        }
        //不合格数量
        BigDecimal qcba027 = genIqcDataNew.getQcba027();
        //收料数量
        BigDecimal qcba008 = genIqcDataNew.getQcba008();
        //非特采时 收料数量 != 合格数量时 按合格数量收料
        if (qcba008.compareTo(qcba023) != 0 && genIqcDataNew.getTc().equals(0)) {
            qcba008 = qcba023;
        }
        //特采时不合格数 = 收料数量 - 合格数量
        if (genIqcDataNew.getTc().equals(1)) {
            qcba027 = qcba008.subtract(qcba023);
        }

        if (slCallbackList.size() > 1) {
            //由于数量是合并，需要计算后回写
            for (SlCallbackListVo slCallbackListVo : slCallbackList) {
                GenIqcDataVo genIqcDataVoReq = BeanUtil.copyProperties(genIqcDataNew, GenIqcDataVo.class);
                //防止单号重复这里回写单号为：质检单号 + 报检项次
                if (genIqcDataNew.getTc() == 1) {
                    genIqcDataVoReq.setQcbaud001(genIqcDataVoReq.getQcbaud001() + "-tc-" + slCallbackListVo.getPmdtseq() );
                } else {
                    genIqcDataVoReq.setQcbaud001(genIqcDataVoReq.getQcbaud001() + '-' + slCallbackListVo.getPmdtseq() );
                }
                genIqcDataVoReq.setQcba900(genIqcDataNew.getQcba900());
                genIqcDataVoReq.setQcba001(slCallbackListVo.getPmdsdocno());
                genIqcDataVoReq.setQcba002(slCallbackListVo.getPmdtseq());

                //剩余可收数量 收料数量-允收数量-验退数量
                BigDecimal subtract = slCallbackListVo.getPmdt020().subtract(slCallbackListVo.getPmdt053()).subtract(slCallbackListVo.getPmdt055());
                if (BigDecimal.ZERO.compareTo(subtract) > 0){
                    continue;
                }
                //合格： 合格数量>收料数量:收料数量 else 合格数量
                if (qcba008.compareTo(subtract) > 0) {
                    //收料数量大于等于本项次的数量
                    genIqcDataVoReq.setQcba008(subtract);
                    qcba008 = qcba008.subtract(subtract);
                    genIqcDataVoReq.setQcba023(subtract);
                    genIqcDataVoReq.setQcba027(BigDecimal.ZERO);
                } else {
                    genIqcDataVoReq.setQcba008(qcba008);
                    genIqcDataVoReq.setQcba023(qcba008);
                    genIqcDataVoReq.setQcba027(BigDecimal.ZERO);
                    qcba008 = BigDecimal.ZERO;
                }
                genIqcDataVoList.add(genIqcDataVoReq);
                if (qcba008.compareTo(BigDecimal.ZERO) == 0) {
                    break;
                }
            }
        } else {
            SlCallbackListVo slCallbackListVo = slCallbackList.get(0);
            genIqcDataNew.setQcba001(slCallbackListVo.getPmdsdocno());
            genIqcDataNew.setQcba002(slCallbackListVo.getPmdtseq());
            genIqcDataNew.setQcba008(qcba008);
            genIqcDataNew.setQcba027(qcba027);
            genIqcDataNew.setQcba900(genIqcDataNew.getQcba900());
//            genIqcDataNew.setQcba008(slCallbackListVo.getPmdt020());
            if (genIqcDataNew.getTc() == 1) {
                genIqcDataNew.setQcbaud001(genIqcDataNew.getQcbaud001() + "-tc-" + slCallbackListVo.getPmdtseq() +'-');
            } else {
                genIqcDataNew.setQcbaud001(genIqcDataNew.getQcbaud001() + '-' + slCallbackListVo.getPmdtseq() +'-');
            }
            genIqcDataVoList.add(genIqcDataNew);
        }

        //计算后为空则不回写
        if (CollUtil.isEmpty(genIqcDataVoList)) {
            wmsPurchaseNewMapper.updateStCheckTcOpflg(genIqcDataNew.getQcbaud001(), 2, "非常见的数据处理问题，请联系开发人员处理");
            return;
        } else {
            //整单改为带返回状态防止下一次查询到该数据
            if (genIqcDataNew.getTc().equals(1)) {
                wmsPurchaseNewMapper.updateStCheckTcOpflg(genIqcDataNew.getQcbaud001(), 3, "erp待返回");
            } else {
                wmsPurchaseNewMapper.updateStCheckOpflg(genIqcDataNew.getQcbaud001(), 3, "erp待返回");
            }
        }
        //不合格数量插入
        if (qcba027.compareTo(BigDecimal.ZERO) > 0) {
            for (GenIqcDataVo genIqcDataVo : genIqcDataVoList) {
                if (qcba027.compareTo(genIqcDataVo.getQcba008()) > 0) {
                    //不合格数量大于等于本项次的数量
                    genIqcDataVo.setQcba027(genIqcDataVo.getQcba008());
                    genIqcDataVo.setQcba023(BigDecimal.ZERO);
                    qcba027 = qcba027.subtract(genIqcDataVo.getQcba008());
                } else {
                    genIqcDataVo.setQcba023(genIqcDataVo.getQcba008().subtract(qcba027));
                    genIqcDataVo.setQcba027(qcba027);
                    qcba027 = BigDecimal.ZERO;
                }

                if (genIqcDataVo.getQcba027().compareTo(genIqcDataVo.getQcba023()) == 0){
                    genIqcDataVo.setQcba023(BigDecimal.ZERO);
                }
                if (qcba027.compareTo(BigDecimal.ZERO) == 0) {
                    break;
                }
            }
        }
    }


    public static void main(String[] args) {
        List<SlCallbackListVo> list = new ArrayList<>();
        list.add(SlCallbackListVo.builder().pmdt020(new BigDecimal("9")).build());
        list.add(SlCallbackListVo.builder().pmdt020(new BigDecimal("8")).build());
        list.add(SlCallbackListVo.builder().pmdt020(new BigDecimal("5")).build());
        list.add(SlCallbackListVo.builder().pmdt020(new BigDecimal("6")).build());
        list.add(SlCallbackListVo.builder().pmdt020(new BigDecimal("4")).build());
        list.add(SlCallbackListVo.builder().pmdt020(new BigDecimal("3")).build());
        list.add(SlCallbackListVo.builder().pmdt020(new BigDecimal("7")).build());
        System.out.println(list.size());
        BigDecimal target = new BigDecimal("35");
        List<List<SlCallbackListVo>> result = findCombinations(list, target);
        for (List<SlCallbackListVo> combination : result) {
            System.out.println(combination);
        }
    }

    public static List<List<SlCallbackListVo>> findCombinations(List<SlCallbackListVo> list, BigDecimal target) {
        List<List<SlCallbackListVo>> result = new ArrayList<>();
        findCombinationsHelper(list, target, 0, new ArrayList<>(), result);
        return result;
    }

    private static void findCombinationsHelper(List<SlCallbackListVo> list, BigDecimal target, int startIndex, List<SlCallbackListVo> currentCombination, List<List<SlCallbackListVo>> result) {
        if (target.compareTo(BigDecimal.ZERO) == 0) {
            result.add(new ArrayList<>(currentCombination));
            return;
        }

        for (int i = startIndex; i < list.size(); i++) {
//            int num = list.get(i);
            SlCallbackListVo slCallbackListVo = list.get(i);
            BigDecimal pmdt020 = slCallbackListVo.getPmdt020();
            if (pmdt020.compareTo(target) <= 1) {
                currentCombination.add(list.get(i));
                findCombinationsHelper(list, target.subtract(pmdt020), i + 1, currentCombination, result);
                currentCombination.remove(currentCombination.size() - 1);
            }
        }
    }

    public String deleteGenIqcData(String orderNo) {
        if (ObjectUtil.isEmpty(orderNo)){
            //查询未处理的数据
            orderNo = wmsPurchaseMapper.getCheckmaterialRollback();
        }
        if (ObjectUtil.isEmpty(orderNo)) {
            return "未查询到要反写反写数据";
        }
        //查询erp数据保存进数据表
        wmsPurchaseNewMapper.wmsErpSelectCheckRollback(orderNo);
        List<DeleteGenIqcDataVo> deleteGenIqcDataVos = wmsPurchaseNewMapper.getDeleteGenIqcData(orderNo);
        if (ObjectUtils.isEmpty(deleteGenIqcDataVos) ) {
            log.info("单据：{}未查询到反写数据", orderNo);
            //更新表数据
            wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, "单据：" +orderNo+"未查询到反写数据");
            return "单据：" +orderNo+"未查询到反写数据";
        }
        //查询关联项次是否入库
        List<Integer> collect = deleteGenIqcDataVos.stream().map(DeleteGenIqcDataVo::getPmdtseq).distinct().collect(Collectors.toList());
        DeleteGenIqcDataVo deleteGenIqcDataVo = deleteGenIqcDataVos.get(0);
        Integer count = wmsPurchaseNewMapper.checkIsInput(deleteGenIqcDataVo.getPmdsdocno(),collect);
        if (count > 0){
            log.info("单据：{}关联报检项次已入库，回滚失败", orderNo);
            //更新表数据
            wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, "单据：" +orderNo+"关联报检项次已入库，回滚失败");
            return "单据：" +orderNo+"关联报检项次已入库，回滚失败";
        }
        //找到未删除回填记录
        //----------测试逻辑代码---------
        //----------测试逻辑代码---------
        try {
            String resMessage = soapXmlUtil.getSoapXmlList("GenIqcData", "qcba_t", deleteGenIqcDataVos);
//            String resMessage = "";
            //转换为soap消息
            log.info("删除质检单回写数据:->{}",resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除采购入库送检单单回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                wmsPurchaseMapper.updaCheckZjFlg(orderNo);
                //反审出库单
                wmsPurchaseMapper.updateInstoreByCheckNo(orderNo, "0");
                //删除出库单
                wmsPurchaseMapper.deleteInstoreByCheckNo(orderNo, "0");
                //更新相应表状态为未下发
                wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(orderNo, xmlResp.getMessage(), 0);
                //更新表数据
                wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 1, xmlResp.getMessage());
            } else {
                //更新表数据
                wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, xmlResp.getMessage());
            }
            return xmlResp.getMessage();
        } catch (Exception e) {
            wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, "系统回写异常，请联系开发人员处理");
            e.printStackTrace();
        }
        return "系统异常";
    }

    @Scheduled(cron = "0 */4 * * * ?")//四分钟执行一次
    //@Async(value = "taskExecutor")
    public void deleteGenIqcData() {
            //查询未处理的数据
        String orderNo = wmsPurchaseMapper.getCheckmaterialRollback();
        if (ObjectUtil.isEmpty(orderNo)) {
            return;
        }
        //查询erp数据保存进数据表
        wmsPurchaseNewMapper.wmsErpSelectCheckRollback(orderNo);
        List<DeleteGenIqcDataVo> deleteGenIqcDataVos = wmsPurchaseNewMapper.getDeleteGenIqcData(orderNo);
        if (ObjectUtils.isEmpty(deleteGenIqcDataVos) ) {
            log.info("单据：{}未查询到反写数据", orderNo);
            //更新表数据
            wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, "单据：" +orderNo+"未查询到反写数据");
            return;
        }
        //查询关联项次是否入库
        List<Integer> collect = deleteGenIqcDataVos.stream().map(DeleteGenIqcDataVo::getPmdtseq).distinct().collect(Collectors.toList());
        DeleteGenIqcDataVo deleteGenIqcDataVo = deleteGenIqcDataVos.get(0);
        Integer count = wmsPurchaseNewMapper.checkIsInput(deleteGenIqcDataVo.getPmdsdocno(),collect);
        if (count > 0){
            log.info("单据：{}关联报检项次已入库，回滚失败", orderNo);
            //更新表数据
            wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, "单据：" +orderNo+"关联报检项次已入库，回滚失败");
            return;
        }
        //找到未删除回填记录
        //----------测试逻辑代码---------
        //----------测试逻辑代码---------
        try {
            String resMessage = soapXmlUtil.getSoapXmlList("GenIqcData", "qcba_t", deleteGenIqcDataVos);
//            String resMessage = "";
            //转换为soap消息
            log.info("删除质检单回写数据:->{}",resMessage);
            //log.info("采购入库单回调：{}",resMessage);
            //发送soap消息，并解析结果
            String result;
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("删除采购入库送检单单回调结果: {}", result);
            XmlResp xmlResp = soapXmlUtil.analysisXml(result);
            if (xmlResp.getCode().equals("0")) {
                wmsPurchaseMapper.updaCheckZjFlg(orderNo);
                //反审出库单
                wmsPurchaseMapper.updateInstoreByCheckNo(orderNo, "0");
                //删除出库单
                wmsPurchaseMapper.deleteInstoreByCheckNo(orderNo, "0");
                //更新相应表状态为未下发
                wmsPurchaseMapper.updatePurchaseReceiptCallbackIncomingInspection(orderNo, xmlResp.getMessage(), 0);
                //更新表数据
                wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 1, xmlResp.getMessage());
                //重新拉取erp收货单 exec wms_erp_up_purchase_receipt_slno '[cd_sl*slno]'
                wmsPurchaseMapper.updatePurchaseReceiptByCheckno(orderNo);
            } else {
                //更新表数据
                wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, xmlResp.getMessage());
            }
        } catch (Exception e) {
            wmsPurchaseMapper.updateCheckmaterialRollback(orderNo, 2, "系统回写异常，请联系开发人员处理");
            e.printStackTrace();
        }
    }



    /**
     * 更新erp检验信息
     */
    @Scheduled(cron = "0 */6 * * * ?")//6分钟执行一次
    //@Async(value = "taskExecutor")
    public void updateCodeInfo(){
        List<UpdateCodeInfoVo> updateCodeInfoList = wmsPurchaseNewMapper.getUpdateCodeInfo();
        if (CollUtil.isEmpty(updateCodeInfoList)){
            return;
        }
        String resMessage = soapXmlUtil.getSoapXmlList("UpdateCodeInfo", "imae_t", updateCodeInfoList);
        log.info("更新erp检验信息请求:->{}",resMessage);
        //发送soap消息，并解析结果
        String result;
        try {
            try {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.getUrl());
            } catch (Exception e) {
                result = soapXmlUtil.sendSoapMessageNew(resMessage, erpConfig.URL2);
            }
            log.info("更新erp检验信息返回:->{}",result);
        }catch (Exception e){
            log.error("更新erp检验信息失败:->{}",e.getMessage());
            e.printStackTrace();
        }

    }
}